﻿using FastCreateProject.Helpers;
using System.Diagnostics;

var port = new Random().Next(5000, 9999);
TaskHelper.RunUseThread(() =>
{
    Init(port);
});

var url = $"http://localhost:{port}";
ProcessStart(url);

Console.WriteLine(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
Console.WriteLine($"服务已启动，{url}");
Console.WriteLine("-----------------------------------------------");
Console.WriteLine("按任意键退出");
Console.ReadKey();

void ProcessStart(string url)
{
    var p = new Process();
    p.StartInfo.FileName = "cmd.exe";
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardInput = true;
    p.StartInfo.RedirectStandardOutput = false;
    p.StartInfo.RedirectStandardError = true;
    p.StartInfo.CreateNoWindow = true;
    p.Start();

    p.StandardInput.WriteLine($"start {url}&exit");
    p.StandardInput.AutoFlush = true;
    p.WaitForExit();
    p.Close();
}

void Init(int port)
{
    var option = new StartOption
    {
        Assembly = "FastCreateProject.dll",
        BufferSize = 1024 * 1024,
        Error404Page = "/404.html",
        Error500Page = "/500.html",
        IndexPage = "/index.html",
        Port = port,
        Routes = new List<RouteItem>(),
        StaticFileExtensions = new Dictionary<string, string>()
    };

    InitRoutes(option);

    var server = new Server(option);
    server.Start();
}

void InitRoutes(StartOption option)
{
    option.Routes.Add(new RouteItem
    {
        Level = 0,
        NS = "FastCreateProject.Controllers.Lv0"
    });
}